package br.edu.ufcg.lsd.wbis.ui.client.ui.loggedin.admin.leftmenu.user;
import java.util.List;

import br.edu.ufcg.lsd.wbis.ui.client.beans.UserInfo;
import br.edu.ufcg.lsd.wbis.ui.client.ui.loggedin.DefaultPortal;
import br.edu.ufcg.lsd.wbis.ui.client.ui.loggedin.admin.UserInfoPortlet;
import br.edu.ufcg.lsd.wbis.ui.client.ui.loggedin.admin.searchusers.ShowSearchedUsersTab;
import br.edu.ufcg.lsd.wbis.ui.client.ui.management.InfoManager;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.widgets.TabPanel;

public class SearchUsersCallback implements AsyncCallback<List<UserInfo>> {

	public static final Integer LIMIT_OF_PORTLETS = 9;

	private final DefaultPortal portal;

	private final TabPanel centerPanel;

	private final int section;

	private final ShowSearchedUsersTab tab;

	private final InfoManager<UserInfo> loggedManager;

	public SearchUsersCallback(int section, DefaultPortal portal, ShowSearchedUsersTab tab, TabPanel centerPanel, InfoManager<UserInfo> loggedManager) {
		this.section = section;
		this.portal = portal;
		this.tab = tab;
		this.centerPanel = centerPanel;
		this.loggedManager = loggedManager;
	}

	/**
	 * {@inheritDoc}
	 */
	public void onFailure(Throwable caught) {
		// Do nothing!
	}

	/**
	 * {@inheritDoc}
	 */
	public void onSuccess(List<UserInfo> result) {
		if (result == null) {
			return;
		}
		if (section <= 0 || (section - 1) * LIMIT_OF_PORTLETS >= result.size()) {
			return;
		}
		this.portal.clear();
		try {
			for (int i = (section - 1) * LIMIT_OF_PORTLETS; i < result.size() && i < section * LIMIT_OF_PORTLETS; i++) {
				this.portal.addPortlet(new UserInfoPortlet(result.get(i), centerPanel, loggedManager));
				this.portal.doLayout();
			}
		} catch (IndexOutOfBoundsException e) {
			return;
		}
		this.tab.setSection(section);
	}

}